import { ref, computed, UnwrapRef } from 'vue';
import { useRequest } from 'alova/client';
import { Method } from 'alova';

/**
 * 通用分页请求 Hook（适配 Wot UI）
 * @template T 列表项类型
 * @template P 请求参数类型（必须包含 pageNo 与 pageSize）
 * 
 * @param requestFn 接口请求函数，入参为 P，返回结构需包含 data: { list, total }
 * @param initialParams 除分页参数外的其他初始参数（如搜索关键字、过滤条件等）
 * @param pageSize 每页大小（默认20）
 */
export function usePaginationRequest<T, P extends Record<string, any>>(
	requestFn: (params: P & { pageNo: number; pageSize: number }) => Method<any>,
	initialParams: UnwrapRef<Omit<P, 'pageNo' | 'pageSize'>> = {} as any,
	pageSize = 20
) {
	const pageNo = ref(1);
	const list = ref<T[]>([]);
	const total = ref(0);
	const finished = ref(false);

	// 额外查询参数（如搜索关键字、过滤条件）
	const extraParams = ref(initialParams);

	const { data, send, loading } = useRequest(
		() =>
			requestFn({
				...extraParams.value,
				pageNo: pageNo.value,
				pageSize
			}),
		{ immediate: false }
	);

	const loadmoreState = computed(() => {
		if (finished.value) return 'finished';
		if (loading.value) return 'loading';
		return 'loadmore';
	});

	/**
	 * 加载当前页数据并追加
	 */
	const fetch = async () => {
		await send();

		const responseData = data.value?.data;
		if (!responseData) return;

		const newList: T[] = responseData.list || [];
		total.value = responseData.total || 0;

		list.value.push(...newList);
		finished.value = list.value.length >= total.value;

		pageNo.value++;
	};

	/**
	 * 重置分页并重新加载第一页
	 * @param newParams 可选的新的筛选参数
	 */
	const reset = async (newParams?: Partial<Omit<P, 'pageNo' | 'pageSize'>>) => {
		pageNo.value = 1;
		list.value = [];
		finished.value = false;
		if (newParams) {
			extraParams.value = {
				...extraParams.value,
				...newParams
			};
		}
		await fetch();
	};

	return {
		list,
		loading,
		loadmoreState,
		fetch,
		reset,
		params: extraParams // 如果需要响应式追踪参数
	};
}
